var currentTab;
var currentBookmark;

function parse(url) {
    var title = document.title;
    var desc = '';

    if (!isSupportedProtocol(url)) {
        console.log("not supported protocol");
        return;
    }

    if (document.getSelection) { desc = document.getSelection(); };

    if (desc.toString().length === 0) {
        let descTag = document.querySelector('[name=description]');
        desc = descTag ? descTag.getAttribute('content') : '';
    };

    if (desc.length > 500) {
        desc = desc.slice(0, 500) + '...';
    };

    console.log(url, title, desc);

    new_url = 'https://cubox.pro/web/tool/collection?url='
        + encodeURIComponent(url)
        + '&title=' + encodeURIComponent(title)
        + '&description=' + encodeURIComponent(desc)
        + '&groupId=' + '&tags=' + '&starTarget=false'
        + '&editable=false', 'cubox', 'toolbar=no,    resizable=no,    location=no,    menubar=no,    width=300,    height=100'

    console.log(new_url);
    browser.windows.create({ 
        url: new_url,
        type: "popup",
        width: 300,
        height: 100,
        focused: false
    });


}

function isSupportedProtocol(url) {
    valid_li = ['http:', 'https:']

    for (const item of valid_li){
      if (url.indexOf(item) !== -1){
        return true;
      } 

    }
    return false;

}

function toggleBookmark() {
    let url = null;
    browser.tabs.query({currentWindow: true, active: true})
    .then((tabs) => {
      console.log(tabs[0].url);
      parse(tabs[0].url);
    })


}


browser.browserAction.onClicked.addListener(toggleBookmark);


